package com.spider.admin.service.account;

import com.spider.admin.conf.ResultMessage;
import com.spider.admin.conf.validator.Constants;
import com.spider.admin.exception.SpiderException;
import com.spider.admin.http.entity.PageResult;
import com.spider.admin.service.async.AsyncService;
import com.spider.admin.store.primary.mapper.AccountMapper;
import com.spider.admin.store.primary.mapper.AccountServicePermMapper;
import com.spider.admin.store.primary.model.AccountInfo;
import com.spider.admin.store.primary.model.AccountPermissions;
import com.spider.admin.utils.CommonUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private AccountServicePermMapper accountServicePermMapper;
    @Resource
    private AsyncService asyncService;
    @Override
    public AccountInfo queryAccountByName(String accountName) throws SpiderException {

        return accountMapper.getAccountByName(accountName);
    }


    @Override
    public PageResult<AccountInfo> queryAccounts(
            Integer page,
            Integer pageSize,
            String accountName,
            String realName,
            Integer accountType,
            String accountStatus) throws SpiderException {
        page = page == null || page.intValue() <= 0 ? 1 : page;
        pageSize = pageSize == null ? 10 : pageSize;
        long totalCount = accountMapper.getAccountRecordNum(accountName, realName, accountType, accountStatus,null).longValue();
        int totalPage = (int) Math.ceil((double) totalCount / (double) pageSize);
        page = page > totalPage ? totalPage : page;
        page = page <= 0 ? 1 : page;
        PageResult<AccountInfo> result = new PageResult<>();
        result.setCurrentPage(page);
        result.setPageSize(pageSize);
        result.setTotal(totalCount);
        result.setTotalPage(totalPage);

        List<AccountInfo> records = accountMapper.queryAccounts((page - 1) * pageSize, pageSize, accountName, realName, accountType, accountStatus);
        result.setList(records);

        return result;
    }

    @Override
    public int saveAccount(AccountInfo accountInfo) throws SpiderException {
        String pwd = accountInfo.getPassword();
        pwd = StringUtils.isEmpty(pwd) ? CommonUtil.generatePassword(8) : pwd;
        accountInfo
                .setPid(CommonUtil.getShortUniqueId())
                .setTenantId(CommonUtil.getShortUniqueId())
                .setArchiveStatus(Constants.ACTIVE.getCode())
                .setPassword(CommonUtil.md5(pwd));
        int i = accountMapper.saveAccount(accountInfo);
//        log.info("新增账户：{},登录密码：{}", accountInfo.getAccountName(), pwd);
        asyncService.asyncRefashPermsCache();
        asyncService.asyncRefashServiceInfoCache();
        return i;
    }

    @Override
    public int updateAccount(AccountInfo accountInfo, String accountName) throws SpiderException {
        accountInfo.setArchiveStatus(null);
        long count = accountMapper.getTenantCountByName(accountName, accountInfo.getTenantName());
        if (count > 0) {
            throw new SpiderException(ResultMessage.FAILED_PARAMS_VALIDATE.getCode(), "租户名称已经被占用");
        }
        int i = accountMapper.updateAccount(accountInfo, accountName);
//        log.info("更新账户：{}", accountName);
        asyncService.asyncRefashPermsCache();
        asyncService.asyncRefashServiceInfoCache();
        return i;
    }

    @Override
    public int activeAccount(String accountName) throws SpiderException {
        AccountInfo accountInfo = new AccountInfo();
        accountInfo.setArchiveStatus(Constants.ACTIVE.getCode());
        int i = accountMapper.updateAccount(accountInfo, accountName);
//        log.info("激活账户：{}", accountName);
        asyncService.asyncRefashPermsCache();
        return i;
    }

    @Override
    public int archiveAccount(String accountName) throws SpiderException {
        AccountInfo accountInfo = new AccountInfo();
        accountInfo.setArchiveStatus(Constants.ARCHIVE.getCode());
        int i = accountMapper.updateAccount(accountInfo, accountName);
//        log.info("激活账户：{}", accountName);
        asyncService.asyncRefashPermsCache();
        return i;
    }

    @Override
    public AccountInfo login(String accountName, String password) throws SpiderException {
        AccountInfo accountInfo = accountMapper.getAccountByName(accountName);
        if (accountInfo == null) {
            throw new SpiderException(ResultMessage.FAILED_PARAMS_VALIDATE.getCode(), "当前账户不存在");
        }

        if (!"active".equals(accountInfo.getArchiveStatus())) {
            throw new SpiderException(ResultMessage.FAILED_PARAMS_VALIDATE.getCode(), "账户已经停用，请联系管理员");
        }
        if (!accountInfo.getPassword().equals(CommonUtil.md5(password))) {
            throw new SpiderException(ResultMessage.FAILED_PARAMS_VALIDATE.getCode(), "账户密码验证异常");
        }
        return accountInfo;
    }

    @Override
    public List<AccountPermissions> getAllPerms() throws SpiderException {
        return accountServicePermMapper.getAllActivePermissions();
    }

    @Override
    public String updateAccountPwd(String accountName, String password) throws SpiderException {
        password = StringUtils.isEmpty(password) ? CommonUtil.generatePassword(8) : password;
        int i = accountMapper.updateAccountPwd(CommonUtil.md5(password), accountName);
        if (i == 0) {
            password = "";
        }
        return password;
    }
    @Override
    public int updateAccountByOwner(AccountInfo accountInfo,String accountName)throws SpiderException {
        String pwd=accountInfo.getPassword();
        if(StringUtils.isNotEmpty(pwd)){
            accountInfo.setPassword(CommonUtil.md5(accountInfo.getPassword()));
        }else{
            accountInfo.setPassword(null);
        }
        int count=accountMapper.updateAccountByOwner(accountInfo,accountName);
        asyncService.asyncRefashPermsCache();
        return count;
    }
}

